package com.clickpaas.governmentcloud.service.policymatchextservice.impl;

import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210127152100.model.TPoliciesDTO;
import com.clickpaas.governmentcloud.common.ConstantExt;
import com.clickpaas.governmentcloud.common.ConstantSuggest;
import com.clickpaas.governmentcloud.common.ServerResponse;
import com.clickpaas.governmentcloud.entity.policyEntity.PolicyEntity;
import com.clickpaas.governmentcloud.rules.hitech.HiTechRules;
import com.clickpaas.governmentcloud.service.policymatchextservice.MatchExtService;
import com.clickpaas.governmentcloud.utils.policycondcalutils.PolicyCondCal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @company <上海爱湃斯科技有限公司>
 * @email <zhihui.peng@clickpaas.com>
 * @author huiye
 * @decription: 上海市高新技术企业入库培育
 * @date 2020/12/16 10:31 上午
 */
@Slf4j
@Service
public class HighTechWarehousServiceImpl implements MatchExtService {

    @Resource
    private PolicyCondCal policyCondCal;

    /**
     * 跟政策是否匹配
     * @param policy 政策对象
     * @return ServerResponse<?>
     */
    @Override
    public ServerResponse<?> isMatchSuccess(PolicyEntity policy) {
        /**
         * 建议
         */
        StringBuffer suggest = new StringBuffer();
        /**
         * 返回信息
         */
        ServerResponse<?> serverResponse = ServerResponse.createError(ConstantExt._ERROR_MESSAGE);
        /**
         * 评分
         */
        Integer score = ConstantExt._ZERO;
        /**
         * 是否快速匹配：Y->true,N->false
         */
        boolean isQuickMatch = ConstantExt.QUICK_MATCH.equals(policy.getType());
        /**
         *  必要条件判断
         */
        HashMap hashMap = necessCondi(policy);
        /**
         * 必要条件对快速匹配数据做处理（精确匹配、快速匹配）
         */
        boolean ifNecess=Boolean.parseBoolean(hashMap.get(ConstantExt._NECESS).toString());
        if(!ifNecess && isQuickMatch){
            return serverResponse;
        }
        /**
         * 累加必要条件评分
         */
        score = score + Integer.parseInt(hashMap.get(ConstantExt._SCORE).toString());
        suggest.append(hashMap.get(ConstantExt._SUGGEST).toString());

        HashMap suggAndScore = getScore(policy);
        /**
         * 累加评分
         */
        score = score + Integer.parseInt(suggAndScore.get(ConstantExt._SCORE).toString());
        /**
         * 评分为0，快速匹配不展示数据
         */
        if(score <= 0 && isQuickMatch){
            return serverResponse;
        }
        /**
         * 添加建议
         */
        suggest.append(suggAndScore.get(ConstantExt._SUGGEST).toString());
        /*if (suggest.length() == 0 && score >= 90) {
            suggest.append("建议申报");
        }*/

        /**
         * 快速匹配不添加建议
         */
        if (isQuickMatch){
            suggest = new StringBuffer();
        }
        /**
         * 必要条件不满足得0分
         */
        if(!ifNecess){
            score = 0;
        }
        return insertPolicyData(policy,score,suggest,serverResponse);
    }

    /**
     * 计算企业评分
     *
     * @param policy
     * @return
     */
    @Override
    public HashMap getScore(PolicyEntity policy) {
        HashMap<String, Object> returnValue = new HashMap<>();
        Integer score = ConstantExt._ZERO;
        StringBuffer suggest = new StringBuffer();

        /**
         * 自主知识产权
         * I类≧1  Ⅱ类>6	27分
         * Ⅱ类≧6	24分
         * Ⅱ类≧4	18分
         * Ⅱ类≧3	12分
         * Ⅱ类≧2	6分
         * Ⅱ类<2	0分
         */
        if(policyCondCal.IntellPropertyFirst(policy)>0
                && policyCondCal.IntellPropertySecond(policy)>6){
            score+=27;
        }else if(policyCondCal.IntellPropertySecond(policy)>=6){
            score+=24;
        }else if(policyCondCal.IntellPropertySecond(policy)>=4){
            score+=18;
        }else if(policyCondCal.IntellPropertySecond(policy)>=3){
            score+=12;
        }else if(policyCondCal.IntellPropertySecond(policy)>=2){
            score+=6;
        }
        if (policyCondCal.IntellPropertySecond(policy)<=4){
            suggest.append(ConstantSuggest._HITECH_INTELLECTUAL);
        }

        /**
         * 参与标准制定（国家、地方、行业）数量
         */
        if (null != policy.getParticipateDevelopment()
                && policy.getParticipateDevelopment()>0){
            score+=2;
        }

        /**
         * 科技成果转化（项）
         */
        if (null != policy.getTechnologicalAchievements()){
            Integer technologicalAchievements = policy.getTechnologicalAchievements();
            if (technologicalAchievements != null) {
                if (technologicalAchievements >= 15) {
                    score += 27;
                } else if (technologicalAchievements >= 12) {
                    score += 22;
                } else if (technologicalAchievements >= 9) {
                    score += 16;
                } else if (technologicalAchievements >= 6) {
                    score += 10;
                } else if (technologicalAchievements >= 3) {
                    score += 5;
                } else if (technologicalAchievements < 3) {
                    score += 0;
                }
            }
            if (technologicalAchievements <= 9) {
                suggest.append(ConstantSuggest._HITECH_ACHIEV_TRANS);
            }
        }

        /**
         * 是否建立制定并完善《企业研发的组织管理制度》等研发管理制度体系（知识产权保护、人才引进培养、创新激励）
         */
        if (StringUtils.isNotBlank(policy.getFormulatedAndImproved())){
            if (ConstantExt._YES.equals(policy.getFormulatedAndImproved())) {
                score += 12;
            }
        }

        /**
         * 是否同1所以上大学或科研院校签订产学研合作协议
         */
        if (StringUtils.isNotBlank(policy.getResearchInstitution())){
            if (ConstantExt._YES.equals(policy.getResearchInstitution())) {
                score += 2;
            }
        }

        /**
         * 是否有研发场地、研发设备等
         */
        if (StringUtils.isNotBlank(policy.getResearchAndDevelopmentSite())){
            if (ConstantExt._YES.equals(policy.getResearchAndDevelopmentSite())) {
                score += 2;
            }
        }

        /**
         * 净资产增长率
         */
        if (null != policy.getGrowthRateOfNetAssets()){
            if (policy.getGrowthRateOfNetAssets() >= 35) {
                score += 10;
            } else if (policy.getGrowthRateOfNetAssets() >= 25) {
                score += 8;
            } else if (policy.getGrowthRateOfNetAssets() >= 15) {
                score += 6;
            } else if (policy.getGrowthRateOfNetAssets() >= 5) {
                score += 4;
            } else if (policy.getGrowthRateOfNetAssets() >= 0) {
                score += 2;
            } else if (policy.getGrowthRateOfNetAssets() <= 0) {
                score += 0;
            }
        }

        /**
         * 前3年主营业务收入平均增长率=[(去年主营业务收入/大前年主营业务收入）^1/3－1]×100%
         */
        double rateIncome = policyCondCal.aveGrowthRateIncome(policy);
        if (rateIncome >= 35) {
            score += 10;
        } else if (rateIncome >= 25) {
            score += 8;
        } else if (rateIncome >= 15) {
            score += 6;
        } else if (rateIncome >= 5) {
            score += 4;
        } else if (rateIncome >= 0) {
            score += 2;
        } else if (rateIncome <= 0) {
            score += 0;
        }

        returnValue.put(ConstantExt._SCORE,score);
        returnValue.put(ConstantExt._SUGGEST,suggest);
        return returnValue;
    }

    /**
     * 写入匹配结果
     *
     * @param policy
     * @return
     */
    @Override
    public ServerResponse insertPolicyData(PolicyEntity policy,Integer score,StringBuffer suggest,ServerResponse serverResponse) {

        /**
         * 查询当前政策信息
         */
        TPoliciesDTO policyInfo = policyCondCal.getPolicyInfo(ConstantExt._HIGH_TECH_WAREHOUSING_CULTIVA);
        if (null == policyInfo) {
            log.info("政策：【{}】查询不到",ConstantExt._HIGH_TECH_WAREHOUSING_CULTIVA);
            return serverResponse;
        }
        policyCondCal.insertCommonPolicyData(policy, policyInfo, score, suggest);
        return ServerResponse.createSuccess(ConstantExt._SUCCESS_MESSAGE);
    }

    /**
     * 必要条件(精确匹配)
     * @param policy
     * @return
     */
    @Override
    public HashMap necessCondi(PolicyEntity policy){
        HashMap<String, Object> map = new HashMap<>();
        Integer score = ConstantExt._ZERO;
        map.put(ConstantExt._NECESS,true);
        StringBuffer suggStr = new StringBuffer();

        /**
         * 是否快速匹配：Y->true,N->false
         */
        boolean isQuickMatch = ConstantExt.QUICK_MATCH.equals(policy.getType());
        //快速匹配标识,必要条件：缺失字段默认给满分，有值进行判断
        if (isQuickMatch && null != policy.getRegisteredTime()){
            //TODO
        }else {
            //注册时间>1年
            if (!policyCondCal.ifCreateMuchYear(policy,1*365)) {
                map.put(ConstantExt._NECESS,false);
                suggStr.append(ConstantSuggest._HTEN_RD_REGIST_DATE);
            }
        }

        if (isQuickMatch && (null == policy.getDpersonnel() || null == policy.getEmpTotal())){
            //TODO
        }else {
            //研发人员占比=研发技术人员/员工总数×100%
            if (policyCondCal.RDPersonRate(policy)<=5){
                map.put(ConstantExt._NECESS,false);
                suggStr.append(ConstantSuggest._HTEN_RD_PERSON);
            }
        }

        if (isQuickMatch && ( null == policy.getBusinessIncomeOfLastYear()
                || null == policy.getDexpensesInTheYearBefore()
                || null == policy.getDexpensesOfThePreviousYear()
                || null == policy.getDexpensesLastYear()
                || null == policy.getYearBeforeTheUniversity()
                || null == policy.getBusinessIncomeOfThePpreviousYear() )){
            //TODO
        }else {
            //近3年研发费用占比
            if (policyCondCal.RDPersonCostRate(policy)<3){
                map.put(ConstantExt._NECESS,false);
                suggStr.append(ConstantSuggest._HTEN_RD_EXPENSES);
            }
        }

        if (isQuickMatch && (null == policy.getHighTechProductsOfLastYear()
                || null == policy.getBusinessIncomeOfLastYear())){
            //TODO
        }else {
            //上年度高新产品和服务收入占比
            if (policyCondCal.RDRevenueRatioLastYear(policy)<40){
                map.put(ConstantExt._NECESS,false);
                suggStr.append(ConstantSuggest._HTEN_INCOME);
            }
        }

        if (isQuickMatch && StringUtils.isBlank(policy.getDishonesty())){
            //TODO
        }else {
            //是否存在违法违规失信行为
            if (!policyCondCal.isIllegal(policy)){
                map.put(ConstantExt._NECESS,false);
            }
        }

        //所属行业
        if (isQuickMatch && (null == policy.getIndustrys() || policy.getIndustrys().size()<=0) ){
            //TODO
        }else {
            if (!HiTechRules.containHighTechField(policy.getIndustrys())){
                map.put(ConstantExt._NECESS,false);
            }
        }

        map.put(ConstantExt._SCORE,score);
        map.put(ConstantExt._SUGGEST,suggStr);
        return map;
    }
}
